package cn.cxj.basic.controller;

import cn.cxj.basic.util.AjaxResult;
import cn.cxj.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件操作接口
 * @author chenxinjie
 */
@RestController
@RequestMapping("/fastDfs")
@Api(tags = "文件上传接口",description = "文件上传接口详细描述")
public class FastDfsController {

    /**
     * 文件上传接口
     * @param file 文件参数
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败!");
        }
    }

    /**
     * 删除文件接口
     * @param path 删除的路径地址
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){
        try {
            String pathTmp = path.substring(1);
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
            String fileName = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastDfsUtil.delete(groupName, fileName);
            System.out.println("删除成功!");
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!");
        }
    }
}
